-module(tools).
-export([ansi2utf8/1,ansi2utf8_flatten/1,get_param/3,get_param/2,toString/2,replace/3]).

toString(datetime,{{Year,Month,Day},{Hour,Min,Sec}}) ->
	io_lib:format("~10B-~10B-~10B ~10B:~10B:~10B",[Year,Month,Day,Hour,Min,Sec]);
toString(_,_) ->
	"invalid".
replace(OriginalString, Pattern, Replace) ->
	case re:replace(OriginalString,Pattern,Replace) of
	[A,B|C] when is_binary(A) ->
		lists:flatten([binary_to_list(A),binary_to_list(B)
											|
											case C of
											[] ->
												[];
											Other ->
												binary_to_list(Other)
											end]);
	_ -> 
		OriginalString
	end.
		
ansi2utf8_flatten(L) ->
	ansi2utf8_A(lists:flatten(L),[]).
	
ansi2utf8(L) ->
	ansi2utf8_A(L,[]).

ansi2utf8_A([],R) ->
	R;
ansi2utf8_A([B],R) when B >= 128 andalso B < 256 ->
	R ++ [B];
	
ansi2utf8_A([B1|LL],R) when B1 >= 128 andalso B1 < 256 ->
	[B2|LLL] = LL,
	U = codeconv:conv([B1,B2]),
	ansi2utf8_A(LLL,R ++ U);
ansi2utf8_A([B|LL],R) ->
	ansi2utf8_A(LL,R ++ [B]).
get_param(L,Param) ->
	get_param(L,Param,"").
get_param(L,Param,Default) ->
	case lists:keyfind(Param,1,L) of 
	{Param,V} ->
		V;
	_ ->
		Default
	end.